const Product = require('../modules/product');

exports.getProductList = (req, res, next) => {
    req.user.getProducts()
    .then(products => {
        res.render('admin/product-list', {
            prods: products,
            path: '/admin/product-list',
            pageTitle: '管理产品'
        })
    })
    .catch(err => console.log(err))
}
exports.getEditProduct = (req, res, next) => {
    const prodId = req.params.prodId;
    if (prodId) {
        req.user.getProducts({ where: { id: prodId } })
        // Product.findByPk(prodId)
        .then(products => {
            res.render('admin/edit-product', {
                product: products[0],
                pageTitle: '编辑产品',
                path: '/admin/product-list',
                isEdit: true
            });
        })
        .catch(err => console.log(err))
    } else {
        res.render('admin/edit-product', {
            product: {},
            pageTitle: '添加产品', 
            path: '/admin/add-product',
            isEdit: false
        });
    }
}

exports.postEditProduct = (req, res, next) => {
    const { id, title, imageUrl, price, description } = req.body;
    Product.findByPk(id)
    .then(product => {
        if (product) {
            product.set({
                title, 
                imageUrl, 
                price, 
                description
            })
            return product.save();
        } else {
            return req.user.createProduct({
                title, 
                imageUrl, 
                price, 
                description
            })
        }
    })
    .then(() => {
        res.redirect('/admin/product-list');
    })
    .catch(err => console.log(err))
}

exports.postDeleteProduct = (req, res, next) => {
    const prodId = req.body.prodId;
    Product.findByPk(prodId)
    .then(content => {
        return content.destroy();
    })
    .then(() => {
        res.redirect('/admin/product-list');
    })
    .catch(err => console.log(err))
}